<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="card">
        <p id="firstName"></p>
        <p id="lastName"></p>
        <p id="age"></p>
    </div>
    <script>
        const user = {
            name: '张三',
            birth: '1991-1-1'
        }

        function showFirstName() {
            document.querySelector('#firstName').textContent = '姓：' + user.name[0]
        }

        function showLastName() {
            document.querySelector('#lastName').textContent = '名：' + user.name.slice(1)
        }

        function showAge() {
            let birthData = new Date(user.birth);
            let today = new Date();
            today.setHours(0);
            today.setMinutes(0);
            today.setMilliseconds(0);
            let thisYearBirth = new Date(today.getTime() - birthData.getTime());
            let age = Math.abs(thisYearBirth.getUTCFullYear() - 1970)
            document.querySelector('#age').textContent = '年龄：' + age;
        }

        // 初始化
        showFirstName()
        showLastName()
        showAge();

        let initialName = user.name
        Object.defineProperty(user, 'name', {
            get: function () {
                return initialName
            },
            set: function (val) {
                //自动调用依赖该属性的函数
                initialName = val
                showFirstName()
                showLastName()
            }
        })
        // 1、修改name,希望自动调用依赖该属性的函数
        user.name = '李四'

        // 2、修改birth,希望自动调用依赖该属性的函数
        let initialBirth = user.birth;
        Object.defineProperty(user, 'birth', {
            get: function () {
                return initialBirth
            },
            set: function (val) {
                //自动调用依赖该属性的函数
                initialBirth = val
                showAge()
            }
        })
        user.birth = '1988-7-7';

    </script>
</body>

</html>